<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAdd">添加补单</el-button>
    <el-button type="warning" @click="handleEmail">邮件内容</el-button>
    <el-button v-if="checkPermission(permissionRoles.supplement_pass)" type="success" icon="el-icon-s-check" class="filter-item" @click="pass()">批量审核</el-button>
    <el-button v-if="checkPermission(permissionRoles.supplement_del)" class="filter-item" type="danger" icon="el-icon-close" @click="handleDelete">批量删除</el-button>
    <el-select v-model="listQuery.sid" class="filter-item" style="width: 130px;" filterable clearable :loading="loading" placeholder="选择区服">
      <el-option v-for="item in serverList" :key="item.sid" :label="item.name+'('+item.sid+')'" :value="item.sid"></el-option>
    </el-select>
    <el-input v-model="listQuery.actorId" class="filter-item" style="width: 150px;" placeholder="角色ID" />
    <el-date-picker v-model="listQuery.createtime[0]" class="filter-item" type="date" style="width: 140px;" placeholder="开始时间"></el-date-picker>-
    <el-date-picker v-model="listQuery.createtime[1]" class="filter-item" type="date" style="width: 140px;" placeholder="结束时间"></el-date-picker>
    <el-button class="filter-item" type="primary" plain icon="el-icon-search" @click="handleFilter">搜索</el-button>

    <el-table v-loading="listLoading" :data="list" class="mt-15" height="720" border :cell-class-name="cellClassNameFn" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column label="订单号" prop="orderid" align="center"></el-table-column>
      <el-table-column label="订单档位" prop="recharge_name" align="center"></el-table-column>
      <el-table-column label="订单金额" prop="order_amount" align="center"></el-table-column>
      <el-table-column label="订单支付金额" prop="pay_amount" align="center"></el-table-column>
      <el-table-column label="订单时间" prop="order_dt" align="center"></el-table-column>
      <el-table-column label="服务器" prop="sname" align="center"></el-table-column>
      <el-table-column label="角色ID" prop="actor_id" align="center"></el-table-column>
      <el-table-column label="角色名" prop="actor_name" align="center"></el-table-column>
      <el-table-column label="等级" prop="level" align="center"></el-table-column>
      <el-table-column label="VIP" prop="vip" align="center"></el-table-column>
      <el-table-column label="补单代金券" prop="num" align="center"></el-table-column>
      <el-table-column label="添加时间" prop="create_dt" align="center"></el-table-column>
      <el-table-column label="添加人" prop="create_user" align="center"></el-table-column>
      <el-table-column label="审核时间" prop="review_dt" align="center"></el-table-column>
      <el-table-column label="审核人" prop="reviewer" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button v-if="checkPermission(permissionRoles.supplement_pass) && row.status == 0" type="text" size="small" title="审核" @click="pass(row)">审核</el-button>
          <el-button v-if="checkPermission(permissionRoles.supplement_del) && row.status == 0" type="text" size="small" title="删除" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :visible.sync="dialogVisible" title="添加补单" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="订单选择" prop="orderid">
          <el-select v-model="dataForm.orderid" value-key="orderid" class="defaut-input" filterable clearable @change="selectOrder" @clear="clearOrder">
            <el-option v-for="(item, index) in orderList" :key="index" :label="item.orderid" :value="item" />
          </el-select>
        </el-form-item>
        <el-table v-loading="listLoading" :data="orderInfo" border style="margin-bottom: 20px;">
          <el-table-column label="订单号" prop="orderid" align="center"></el-table-column>
          <el-table-column label="档位ID" prop="recharge_name" align="center"></el-table-column>
          <el-table-column label="订单金额" prop="amount" align="center"></el-table-column>
          <el-table-column label="支付金额" prop="pay_amount" align="center"></el-table-column>
          <el-table-column label="服务器" prop="sname" align="center"></el-table-column>
          <el-table-column label="角色ID" prop="actor_id" align="center"></el-table-column>
          <el-table-column label="角色名" prop="actor_name" align="center"></el-table-column>
        </el-table>
        <el-form-item label="角色ID" prop="actorId">
          <el-input v-model="actorid" :disabled="actorSearch" type="textarea" :autosize="{ minRows: 5, maxRows: 8}" placeholder="请输入角色ID" @blur="handleBlueActorId('1')" />
        </el-form-item>
        <el-table v-loading="listLoading" :data="actorList" border style="margin-bottom: 20px;">
          <el-table-column label="区服" prop="sname" align="center"></el-table-column>
          <el-table-column label="角色ID" prop="actor_id" align="center"></el-table-column>
          <el-table-column label="角色名" prop="name" align="center"></el-table-column>
          <el-table-column label="等级" prop="level" align="center"></el-table-column>
          <el-table-column label="VIP" prop="vip" align="center"></el-table-column>
        </el-table>
        <el-form-item label="订单选项" prop="order_type">
          <el-select v-model="dataForm.order_type" class="defaut-input">
            <el-option label="限时代金卷" value="1" />
            <el-option label="代金卷" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额数量" prop="num">
          <el-input v-model="dataForm.num" class="defaut-input" placeholder="代金卷数量" />
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="emailDialogVisible" title="添加邮件" :close-on-click-modal="false">
      <el-form ref="emailForm" :model="emailForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="邮件标题" prop="title">
          <el-input v-model="emailForm.title" class="defaut-input" placeholder="填写邮件标题" />
        </el-form-item>
        <el-form-item label="邮件内容" prop="content">
          <el-input v-model="emailForm.content" type="textarea" :autosize="{ minRows: 3, maxRows: 8}" style="width: 60%;" />
        </el-form-item>
        <el-form-item label="发送人" prop="sender">
          <el-input v-model="emailForm.sender" class="defaut-input" placeholder="填写发送人" />
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="emailDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="emailConfirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getSupplementList, handleSupplement, handleSupplementEmail, getSupplementEmailList, deleteSupplementEmail, approvedSupplement } from '@/api/gm'
import Pagination from '@/components/Pagination'
import checkPermission from '@/utils/permission'
import { getServerList } from '@/api/ops'
import { getRechargeOrder } from '@/api/statis'
import { checkActor } from '@/api/operator'

const defaultItem = {
  id: '',
  sid: '',
  actor_id: '',
  orderid: '',
  recharge_id: '',
  order_amount: '',
  pay_amount: '',
  order_dt: '',
  actor_name: '',
  level: '',
  vip: '',
  order_type: '',
  num: ''
}
const emailItem = {
  id: '',
  title: '',
  content: '',
  sender: ''
}
export default {
  name: 'DeviceCode',
  components: { Pagination },
  data() {
    return {
      actorSearch: false,
      permissionRoles: this.$store.state.user.permissionRoles,
      listLoading: false,
      loading: false,
      dataForm: Object.assign({}, defaultItem),
      emailForm: Object.assign({}, emailItem),
      rules: {
      },
      listQuery: {
        sid: '',
        actorId: '',
        orderid: '',
        createtime: [],
        page: 1,
        limit: 200
      },
      multipleSelection: [],
      total: 0,
      actorid: '',
      list: [],
      serverList: [],
      orderList: [],
      actorList: [],
      orderInfo: [],
      dialogVisible: false,
      emailDialogVisible: false
    }
  },
  computed: {
  },
  created() {
    this.getServerList()
    let orderid = this.$route.params.orderid
    if (orderid === ':orderid') orderid = ''
    this.listQuery.orderid = orderid
    this.getList()
  },
  methods: {
    checkPermission,
    async getList() {
      this.listLoading = true
      getSupplementList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.getList()
    },
    async getServerList() {
      const res = await getServerList()
      this.serverList = res.data.items
    },
    async geteOrderList() {
      const res = await getRechargeOrder({ status: [-1, 2] })
      this.orderList = res.data.items
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleAdd() {
      this.geteOrderList()
      this.actorList = []
      this.orderInfo = []
      this.actorid = ''
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEmail() {
      this.emailDialogVisible = true
      this.emailForm = Object.assign({}, emailItem)
      getSupplementEmailList().then(response => {
        if (!Array.isArray(response.data)) {
          this.emailForm = response.data
        }
      })
      this.$nextTick(() => {
        this.$refs['emailForm'].clearValidate()
      })
    },
    handleBlueActorId(type) {
      if (this.actorid === '' || this.actorid === undefined) return false
      checkActor({ actor_id: this.actorid, type: 1 }).then(response => {
        if (response.status) {
          this.actorList = response.data
          this.dataForm.sid = response.data[0].sid
          this.dataForm.actor_id = response.data[0].actor_id
          this.dataForm.actor_name = response.data[0].name
          this.dataForm.level = response.data[0].level
          this.dataForm.vip = response.data[0].vip
        }
      })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          handleSupplement(this.dataForm).then(response => {
            if (response.status) {
              this.dialogVisible = false
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getList()
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    emailConfirmSubmit() {
      this.$refs['emailForm'].validate((valid) => {
        if (valid) {
          handleSupplementEmail(this.emailForm).then(response => {
            if (response.status) {
              this.emailDialogVisible = false
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getList()
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    async handleDelete(row) {
      if (this.multipleSelection.length <= 0 && typeof row === 'undefined') {
        this.$message.error('请至少选择一条记录')
        return false
      }

      this.$confirm('你确定要删除吗?', '高风险操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(async() => {
        const d = this.multipleSelection
        if (row) {
          d.push(row)
        }
        deleteSupplementEmail(d).then(response => {
          this.multipleSelection = []
          if (response.status === true) {
            this.$message.success('操作成功!')
            this.getList()
          } else {
            this.$message.error('操作失败!')
          }
        })
      }).catch(err => {
        console.error(err)
      })
    },
    pass(row) {
      if (this.multipleSelection.length <= 0 && typeof row === 'undefined') {
        this.$message.error('请至少选择一条未审核的记录')
        return false
      }

      this.$confirm('你确定审核吗?', '高风险操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.disabled = true
        const d = this.multipleSelection
        if (row) {
          d.push(row)
        }
        approvedSupplement(d).then(response => {
          this.disabled = false
          this.multipleSelection = []
          if (response.status === true) {
            this.$message.success('操作成功!')
            this.getList()
          } else {
            this.$message.error('操作失败!')
          }
        })
      }).catch(err => {
        this.disabled = false
        console.error(err)
      })
    },
    cellClassNameFn(row) {
      if (row.columnIndex === 0 && row.row.status === 1) {
        return 'table-column-hidden'
      }
    },
    clearOrder() {
      this.actorSearch = false
    },
    selectOrder(info) {
      if (info) {
        this.actorSearch = true
      }
      this.orderInfo = [info]
      this.actorid = info.actor_id
      this.handleBlueActorId('0')
      this.dataForm.orderid = info.orderid
      this.dataForm.recharge_id = info.recharge_id
      this.dataForm.order_amount = info.amount
      this.dataForm.pay_amount = info.pay_amount
      this.dataForm.order_dt = info.create_dt
    }
  }
}
</script>
